<?php

ini_set("memory_limit", "100M");
ini_set("max_execution_time", 36000);

require_once('../../config/maptrick.conf.php');
require_once(SITE_ROOT . 'lib/PHT.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');
require_once(SITE_ROOT . 'class/bean/Division.class.php');
require_once(SITE_ROOT . 'class/bean/League.class.php');
require_once(SITE_ROOT . 'class/bean/HLeague.class.php');
require_once(SITE_ROOT . 'class/db/DBCountry.class.php');
require_once(SITE_ROOT . 'class/db/DBDivision.class.php');
require_once(SITE_ROOT . 'class/db/DBLeague.class.php');
require_once(SITE_ROOT . 'class/db/DBHLeague.class.php');

try {
	if ($_GET["pass"] != SCRIPT_PWD) die("Incorrect password");
	
	$HT = new CHPPConnection(CONSUMERKEY, CONSUMERSECRET);
	$HT->setOauthToken(USERTOKEN);
	$HT->setOauthTokenSecret(USERTOKENSECRET);
	
	$dbcountry = new DBCountry();
	$dbdivision = new DBDivision();
	$dbleague = new DBLeague();
	$dbhleague = new DBHLeague();
	
	$countries = $dbcountry->getCountries();
	$hleagues = new ArrayObject();
	
	foreach ($countries as $country) {
	//for second script: other direction
	//$countries_reverse = array_reverse($countries->getArrayCopy());
	//foreach ($countries_reverse as $country) {
		$divisions = $dbdivision->getDivisionsByCountry($country, true);
		foreach ($divisions as $division) {
			$leagues = $dbleague->getLeaguesByDivision($division);
			foreach ($leagues as $league) {
				$hleagueDB = $dbhleague->getHLeague($league->getLeagueID(), time());
				if ($hleagueDB == null) {
					$htLeague = $HT->getLeague($league->getLeagueID());
					$hleague = new HLeague($league, time());
					for ($i=1; $i<=8; $i++) {
						try {
							$htLeagueTeam = $htLeague->getTeam($i);
							$htTeam = $HT->getTeam($htLeagueTeam->getTeamId());
							if ($htTeam->isBot() || $htTeam->getUserId() == 0) {
								$hleague->setNumberBots($hleague->getNumberBots() + 1);
							}
							if ($htTeam->isHtSupporter()) {
								$hleague->setNumberSupporters($hleague->getNumberSupporters() + 1);
							}
						}
						catch (Exception $e) {
							echo "Problem with TeamID " . $htLeagueTeam->getTeamId() . "<br />";
						}
					}
					$hleagues->append($hleague);
					if (count($hleagues) >= 100) {
						$dbhleague->saveHLeagues($hleagues);
						$hleagues = new ArrayObject();
					}
					$HT->clearTeams();
					$HT->clearLeagues();
				}
			}
			$dbhleague->saveHLeagues($hleagues);
			$hleagues = new ArrayObject();
		}
		echo $country->getName() . " finished successfully<br />";
	}
	echo "All leagues fetched";
}
catch (Exception $e) {
	echo $e->getMessage();
}

?>